package org.example.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.Data;
import org.example.config.JwtConfig;
import org.example.exception.WechatLoginException;
import org.example.model.User;
import org.example.model.WechatUserInfo;
import org.example.model.request.UserRequest;
import org.example.repository.UserRepository;
import org.example.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Data
public class WechatService {

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;


    private final RestTemplate restTemplate;
    private final JwtConfig jwtConfig; // 使用 JwtConfig

    //微信服务接口地址
    private final static String url = "https://api.weixin.qq.com/sns/jscode2session";
    private final AtomicInteger userCount = new AtomicInteger(0); // 计数器用于生成 UID
    private final UserRepository userRepository;


    public WechatService(RestTemplate restTemplate, JwtConfig jwtConfig, UserRepository userRepository) {
        this.restTemplate = restTemplate;
        this.jwtConfig = jwtConfig;
        this.userRepository = userRepository;
    }


    public WechatUserInfo wxLogin(String code) {
        //调用微信接口服务，获取当前微信用户的openid
        Map<String,String> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

//        log.info("该微信用户的appid是：{}",appid);
//        log.info("该微信用户的secret是：{}",secret);

        String json = HttpClientUtil.doGet(url,map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        String sessionKey = jsonObject.getString("session_key");
//        log.info("该微信用户的openid是：{}",openid);
//        log.info("该微信用户的sessionKey是：{}",sessionKey);

        // 根据openid是否为空判断登录是否成功
        if(openid == null) throw new WechatLoginException("Login failed");

        // 根据openid获取用户，判断该用户是否为新用户
        // 如果是新用户，则完成注册操作
        User user = userRepository.findByOpenid(openid);
        if(user == null){
            user = new User();
            user.setOpenid(openid);
            user.setSessionKey(sessionKey);

            userRepository.save(user);
//            log.info("操作数据库：执行插入操作");
        }

        WechatUserInfo wechatUserInfo = new WechatUserInfo();
        BeanUtils.copyProperties(user,wechatUserInfo);

        return wechatUserInfo;
    }




    public int registerUser() {
        return userCount.incrementAndGet(); // 增加计数并返回 UID,后续如果改成uid是我们自己生成要用到，现在用的uid是openid
    }

    public String getTokenByOpenid(String openid) {
        User user = userRepository.findByOpenid(openid);
        return user != null ? user.getToken() : null;
    }

    /**
     * 设置用户名和头像
     * @param userRequest
     */
    public void setUserInfo(UserRequest userRequest) {
        //解析token  得到自己的openid
        // 获取当前请求
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 从请求头中获取Authorization的值
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            throw new RuntimeException();
        }

        // 获取token，去掉 "Bearer " 前缀
        String token = authorizationHeader.substring(7);
        // 移除可能存在的大括号
        if (token.startsWith("{") && token.endsWith("}")) {
            token = token.substring(1, token.length() - 1);
        }

        Claims claims;
        try {

            claims = Jwts.parser()
                    .setSigningKey(jwtConfig.getJwtSecret())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new RuntimeException();
        }
        String myOpenid = String.valueOf(claims.getSubject());//获取token中的openid
        User user = userRepository.findByOpenid(myOpenid);
        user.setNickname(userRequest.getNickname());
        user.setAvatarUrl(userRequest.getAvatarUrl());
        userRepository.save(user);
    }

}
